package com.atguigu.exam.service.impl;

import com.atguigu.exam.entity.Banner;
import com.atguigu.exam.mapper.BannerMapper;
import com.atguigu.exam.service.BannerService;
import com.atguigu.exam.service.FileUploadService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * 轮播图服务实现类
 */
@Service
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner> implements BannerService {
    @Autowired
    private FileUploadService fileUploadService;

    @Override
    public String uploadBannerImage(MultipartFile file) throws Exception {
        //1.非空校验
        if (file == null || file.isEmpty()) {
            throw new RuntimeException("上传轮播图图片失败！原因：上传文件为空!!");
        }
        //2.格式校验
        if (!file.getContentType().startsWith("image")) {
            throw new RuntimeException("上传轮播图图片失败！原因：上传文件类型错误，非图片!!");
        }
        //3.调用核心业务
        String url = fileUploadService.uploadFile("banners", file);
        //4.返回地址
        return url;
    }

    @Override
    public void addBanner(Banner banner) throws Exception {
        //1.检查默认值 isActive=true sortOrder=1
//        if (banner.getIsActive() == null) {
//            banner.setIsActive(true);
//        }
//        if (banner.getSortOrder() == null) {
//            banner.setSortOrder(5);
//        }
        //2.creatTime updateTime isDeleted
//        banner.setCreateTime(new Date());
//        banner.setUpdateTime(new Date());
//        banner.setIsDeleted((byte) 0);
//3.继续保存
        boolean saved = save(banner);
        if (!saved) {
            throw new Exception("轮播图保存失败");
        }
    }

    @Override
    public void updateBanner(Banner banner) throws Exception {
        if (banner.getIsActive() == null) {
            banner.setIsActive(true);
        }
        if (banner.getSortOrder() == null) {
            banner.setSortOrder(5);
        }
        boolean updated = updateById(banner);
        if (!updated) {
            throw new Exception("轮播图修改失败！");
        }
    }
}